package com.yunc.user.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.common.core.constant.BaseConstant;
import com.yunc.common.core.result.R;
import com.yunc.user.sys.entity.SysMenu;
import com.yunc.user.sys.entity.SysRole;
import com.yunc.user.sys.entity.dto.SysMenuDTO;
import com.yunc.user.sys.entity.dto.SysMenuTreeDTO;
import com.yunc.user.sys.service.ISysMenuService;
import com.yunc.user.sys.service.ISysRoleService;
import com.yunc.user.sys.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 菜单
 *
 * @author taocongcong
 * @create 2017-12-15 13:50
 */
@Slf4j
@RestController
@RequestMapping("sysMenu")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMenuController {

    private final ISysMenuService sysMenuService;
    private final ISysRoleService sysRoleService;
    private final ISysUserService sysUserService;

    @GetMapping("/list")
    public R list(SysMenu sysMenu) {
        QueryWrapper<SysMenu> ew = new QueryWrapper<SysMenu>().orderByAsc("order_num");
        if (StringUtils.isNotEmpty(sysMenu.getName())) {
            ew.like("name", sysMenu.getName());
        }
        List<SysMenu> sysMenuList = sysMenuService.list(ew);
        log.info("在{}查询所有菜单", DateUtil.formatDateTime(new Date()));
        return R.ok().put("data", sysMenuList);
    }

    @GetMapping("/list/{roleId}")
    public R roleMenuTreeData(@PathVariable String roleId, SysMenu sysMenu) {
        List<Map<String, Object>> tree = sysMenuService.roleMenuTreeData(sysMenu, roleId);
        return R.ok().put("tree", tree);
    }

    @GetMapping("queryMenuList")
    public R queryMenuList(String name) {
        // 下拉树
        List<SysMenu> sysMenuList = sysMenuService.queryUserMenuByNameList(name);
        return R.ok().put("data", sysMenuList);
    }

    @GetMapping("queryMenuTreeList")
    public R queryMenuTreeList(String userId) {
        // 下拉树
        List<SysMenuTreeDTO> sysMenuList = sysMenuService.queryMenuTreeList();
        List<String> menuIds = sysUserService.queryMenuIdByRoleId(userId);
        return R.ok().put("data", sysMenuList).put("menuIds", menuIds);
    }

    @GetMapping("queryMenuTreeByRoleIdList")
    public R queryMenuTreeByRoleIdList(String roleId) {
        // 下拉树
        List<SysMenuTreeDTO> sysMenuList = sysMenuService.queryMenuTreeList();
        List<String> menuIds;
        if (roleId == null) {
            menuIds = new ArrayList<>();
        } else {
            menuIds = sysUserService.queryMenuIdByRoleId(roleId);
        }
        return R.ok().put("data", sysMenuList).put("menuIds", menuIds);
    }

    @GetMapping("/listAuth")
    public R queryMenuTreeForAuth(String roleId, SysMenu sysMenu) {
        SysRole sysRole = sysRoleService.getById(roleId);
        QueryWrapper<SysMenu> ew = new QueryWrapper<>(sysMenu);
        ew.orderByAsc("order_num");
        List<SysMenu> sysMenuList = sysMenuService.list(ew);
        List<Long> menuIdList = new ArrayList<>();
        if (roleId != null) {
            List<String> menuIdStrList = sysUserService.queryMenuIdByRoleId(roleId);
            if (CollUtil.isNotEmpty(menuIdStrList)) {
                for (String menuId : menuIdStrList) {
                    menuIdList.add(Long.parseLong(menuId));
                }
            }
        }
        return R.ok().put("sysRole", sysRole).put("sysMenuList", sysMenuList).put("menuIdList", menuIdList);
    }

    @GetMapping(value = "/queryCurrentUserMenuList")
    public R queryUserMenuList() {
        // 根据当前用户查询
        List<SysMenuDTO> sysMenuList = sysMenuService.queryUserMenuDtoList("1");
        // Set<String> permissions = sysUserService.queryUserMenuPermsList(userId);
        return R.ok().put("data", sysMenuList);
    }

    @GetMapping("/page")
    public Page<SysMenu> page(Page<SysMenu> page, SysMenu sysMenu) {
        sysMenuService.page(page, new QueryWrapper<>(sysMenu));
        return page;
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    public R info(@PathVariable String menuId) {
        SysMenu menu = sysMenuService.getById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @CacheEvict(value = {"userMenus", "userMenuAll", "userMenuTreeAll", "sysUserRoleMenus"}, allEntries = true)
    public R save(SysMenu menu) {
        menu.setRemoveTag(BaseConstant.REMOVE_N);
        menu.setCreateTime(new Date());
        boolean flag = sysMenuService.save(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @PutMapping(value = "/update")
    @CacheEvict(value = {"userMenus", "userMenuAll", "userMenuTreeAll", "sysUserRoleMenus"}, allEntries = true)
    public R update(SysMenu menu) {
        boolean flag = sysMenuService.updateById(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{menuId}")
    @CacheEvict(value = {"userMenus", "userMenuAll", "userMenuTreeAll", "sysUserRoleMenus"}, allEntries = true)
    public R delete(@PathVariable String menuId) {
        return sysMenuService.deleteMenu(menuId);
    }
}
